package com.jianxiu.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jianxiu.bean.Cons;
import com.jianxiu.bean.Roles;
import com.jianxiu.bean.User;
import com.jianxiu.bean.UserView;
import com.jianxiu.dao.mapper.ReportMapper;
import com.jianxiu.dao.mapper.UserMapper;
import com.jianxiu.service.UserService;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private ReportMapper reportMapper;

    @Override
    public User getByOpenId(String openid) {
        return userMapper.getByOpenid(openid);
    }

    @Override
    public User createNewUser(String openId) {
        User user = new User();
        user.setOpenid(openId);
        user.setRole(Roles.COMMON);
        userMapper.create(user);
        return user;
    }

    @Override
    public UserView view(User user) {
        UserView view = new UserView();
        if (user.isAdmin()) {
            Map<String, Object> param = new HashMap();
            param.put("stas", new int[]{0});
            view.setWaitSureCnt(reportMapper.count(param));
            param.put("stas", new int[]{1});
            view.setWaitMainCnt(reportMapper.count(param));
            param.put("stas", new int[]{2});
            view.setWaitOverCnt(reportMapper.count(param));
            param.put("stas", new int[]{9});
            view.setOverCnt(reportMapper.count(param));
        } else if (user.isWork()) {
            Map<String, Object> mainParam = new HashMap();
            mainParam.put("stas", new int[]{1});
            mainParam.put("mainId", user.getId());
            view.setMyWaitMainCnt(reportMapper.count(mainParam));
            mainParam.put("stas", new int[]{2, 9});
            view.setMyOverMainCnt(reportMapper.count(mainParam));
        }
        Map<String, Object> doParam = new HashMap();
        doParam.put("userId", user.getId());
        doParam.put("stas", new int[]{0, 1});
        view.setWaitDoCnt(reportMapper.count(doParam));
        doParam.put("stas", new int[]{2, 9});
        view.setDoCnt(reportMapper.count(doParam));
        return view;
    }

    @Override
    public int update(User user) {
        return userMapper.update(user);
    }

    @Override
    public List<User> listWorks() {
        Map<String, Object> param = new HashMap<>();
        param.put("role", Roles.MAINTAIN);
        param.put("status", Cons.YES);
        return userMapper.list(param);
    }

    @Override
    public List<User> list(Map<String, Object> sp) {
        return userMapper.list(sp);
    }

    @Override
    public int count(Map<String, Object> sp) {
        return userMapper.count(sp);
    }

    @Override
    public User get(Long id) {
        return userMapper.getById(id);
    }
}
